//
//  CameraViewController.m
//  HGMM
//
//  Created by @HUI on 15/9/18.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "CameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SVProgressHUD.h"
#import "MyButton.h"
#import "HGPluginUtil.h"
#import "NSString+hui.h"
#import "UIViewExt.h"
#define bottomViewHeight 60




@interface CameraViewController ()
{
    AVCaptureDevice *_cameraAvaible;
    UIScrollView *_imageScroll;
    PhotoPushBlock _photoPushBlock;
}

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureDeviceInput *vidioInput;
@property (nonatomic, strong) AVCaptureStillImageOutput *stillImageOutput;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) UIButton *shutterButton;
@property (nonatomic, strong) UIView *cameraShowView;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) UILabel *textLable;
@property (nonatomic, strong) UIScrollView *imageScrollView;


@end

@implementation CameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    
    [self createCameraView];
    
}





-(id)initWithBlock:(PhotoPushBlock)block{
    if (self = [super init]) {
        _photoPushBlock = block;
        self.imageArray = [NSMutableArray arrayWithCapacity:0];
        [self initialSession];
    }
    return self;
}

-(AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if (device.position == position) {
            return device;
        }
    }
    return nil;
}

-(AVCaptureDevice *)getFrontCamera{
    return [self cameraWithPosition:AVCaptureDevicePositionFront];
}

-(AVCaptureDevice *)getBackCamera{
    return [self cameraWithPosition:AVCaptureDevicePositionBack];
}

-(void)initialSession{
    _cameraAvaible = [self getBackCamera];
    if (!_cameraAvaible) {
        _cameraAvaible = [self getFrontCamera];
    }
    self.session = [[AVCaptureSession alloc]init];
    self.vidioInput = [[AVCaptureDeviceInput alloc]initWithDevice:_cameraAvaible error:nil];
    NSDictionary *outputSetting = [NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc]init];
    self.stillImageOutput.outputSettings = outputSetting;
    
    if ([self.session canAddInput:self.vidioInput]) {
        [self.session addInput:self.vidioInput];
    }
    if ([self.session canAddOutput:self.stillImageOutput]) {
        [self.session addOutput:self.stillImageOutput];
    }
}

-(void)setUpCameraLayer{
    if (!_cameraAvaible) {
        [SVProgressHUD showImage:nil status:@"摄像头故障"];
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    if (!self.previewLayer) {
        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
        UIView * view = self.cameraShowView;
        CALayer * viewLayer = [view layer];
        [viewLayer setMasksToBounds:YES];
        
        CGRect frame = [view frame];
        [self.previewLayer setFrame:frame];
        [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        
        [viewLayer insertSublayer:self.previewLayer below:[[viewLayer sublayers] objectAtIndex:0]];
    }
    
}

-(void)shutterCamera{
    AVCaptureConnection * videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection) {
        return;
    }
    
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == NULL) {
            return;
        }
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:imageData];
        UIImage *newImage = [self addStrWithImage:image str:self.textLable.text];
        [self addImageToScroll:newImage];
    }];
}

-(UIImage *)addStrWithImage:(UIImage *)image str:(NSString *)str{
    UIGraphicsBeginImageContext(self.cameraShowView.frame.size);
    [image drawInRect:self.cameraShowView.frame];
    CGPoint point = CGPointMake(self.textLable.frame.origin.x, self.textLable.frame.origin.y);
    [str drawAtPoint:point withAttributes:nil];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

-(void)saveImageWithImages:(NSArray *)imageArr{
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    NSString *imgName = [NSString stringWithCurrentDate];
    HGPluginUtil *util = [[HGPluginUtil alloc]init];
    NSString *rootPath = [[NSString stringWithFormat:@"%@/image",[util getPluginDataDir:self.pluginId]]stringByAppendingPathComponent:self.path];
    NSError *error = nil;
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:rootPath]) {
        [manager createDirectoryAtPath:rootPath withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            return;
        }
    }
    for (int i = 0; i < imageArr.count; i++) {
        NSString *imgPath = [NSString stringWithFormat:@"%@_%d.jpg",imgName, i];
        NSString *savePath = [rootPath stringByAppendingPathComponent:imgPath];
        NSData *imgData = UIImageJPEGRepresentation(imageArr[i], 1);
        [imgData writeToFile:savePath atomically:YES];
        [arr addObject:savePath];
    }
    _photoPushBlock(arr);
}

-(void)createCameraView{
    
    UIView *bottomView = [self bottomView];
    [self.view addSubview:bottomView];
    
    self.cameraShowView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,HG_SCREEN_WIDTH, HG_SCREEN_HEIGHT - bottomView.height)];
    [self.view addSubview:self.cameraShowView];
    self.imageScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,bottomView.top-80, self.view.frame.size.width, 80)];
    self.imageScrollView.hidden = YES;
    self.imageScrollView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.7];
    [self.view addSubview:self.imageScrollView];
    NSString *str = [NSString stringWithFormat:@"%@\n%@",self.lableText1,self.lableText2];
    self.textLable = [[UILabel alloc]init];
    self.textLable.text = str;
    self.textLable.textAlignment = NSTextAlignmentCenter;
    self.textLable.numberOfLines = 0;
    self.textLable.userInteractionEnabled = YES;
    [self.textLable sizeToFit];
    self.textLable.frame = CGRectMake(self.cameraShowView.frame.size.width - self.textLable.frame.size.width - 20, self.cameraShowView.frame.size.height - self.textLable.frame.size.height - 20, self.textLable.frame.size.width, self.textLable.frame.size.height);
    [self.cameraShowView addSubview:self.textLable];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(lablePan:)];
    [self.textLable addGestureRecognizer:pan];
   
}

-(UIView *)bottomView{
    
    CGFloat bh = bottomViewHeight;
    if (isIphoneX) {
        bh = bottomViewHeight + 34;
    }
    UIView *bottomView=[[UIView alloc]initWithFrame:CGRectMake(0, HG_SCREEN_HEIGHT-bh, HG_SCREEN_WIDTH, bh)];
    bottomView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg"]];
    CGFloat btnWidth = HG_SCREEN_WIDTH/3.0;
    
    for (int i = 0; i < 3; i++) {
        
        MyButton *button = [MyButton buttonWithType:UIButtonTypeCustom];
        
        button.frame = CGRectMake(i * btnWidth + (btnWidth - 40)/2.0,(bottomViewHeight - 40)/2.0 , 40, 40);
        
        
        switch (i) {
            case 0:
                [button setImage:[UIImage imageNamed:@"slide-left"] forState:UIControlStateNormal];
                [button setImage:[UIImage imageNamed:@"slide-left-select"] forState:UIControlStateHighlighted];
                [button addTarget:self action:@selector(goback) forControlEvents:UIControlEventTouchUpInside];
                
                break;
            case 1:
                [button setImage:[UIImage imageNamed:@"xiangji"] forState:UIControlStateNormal];
                [button addTarget:self action:@selector(shutterCamera) forControlEvents:UIControlEventTouchUpInside];
                
                break;
            case 2:
                [button setImage:[UIImage imageNamed:@"slide-plugin"] forState:UIControlStateNormal];
                [button setImage:[UIImage imageNamed:@"slide-plugin-selsct"] forState:UIControlStateHighlighted];
                [button addTarget:self action:@selector(showScroll) forControlEvents:UIControlEventTouchUpInside];
                [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                break;
                
            default:
                break;
        }
        
        [bottomView addSubview:button];
    
    }
    
    
    return bottomView;
}

-(void)goback{
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.imageArray.count > 0) {
            [self saveImageWithImages:self.imageArray];
        }
    }];
}

-(void)showScroll{
    self.imageScrollView.hidden = !self.imageScrollView.hidden;
}

-(void)lablePan:(UIPanGestureRecognizer *)pan{
    self.textLable.center = [pan locationInView:self.cameraShowView];
}

-(void)addImageToScroll:(UIImage *)image{
    [self.imageArray addObject:image];
    self.imageScrollView.contentSize = CGSizeMake(self.imageArray.count * 80, 0);
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(5 + 70 * (self.imageArray.count - 1), 10, 60, 60);
    btn.tag = self.imageArray.count -1 + 100;
    [btn setImage:image forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(imageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.imageScrollView addSubview:btn];
    MyButton *deleteBtn = [MyButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.bounds = CGRectMake(0, 0, 40, 40);
    deleteBtn.center = CGPointMake(btn.frame.size.width - 5, 5);
    deleteBtn.tag = btn.tag + 100;
    [deleteBtn setImage:[UIImage imageNamed:@"icon"] forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(removeImageFromScroll:) forControlEvents:UIControlEventTouchUpInside];
    [btn addSubview:deleteBtn];
}

-(void)removeImageFromScroll:(UIButton *)button{
    [button.superview removeFromSuperview];
    [self.imageArray removeObjectAtIndex:button.tag-200];
    self.imageScrollView.contentSize = CGSizeMake(self.imageArray.count * 80, 0);
}

-(void)imageBtnClick:(UIButton *)button{
    if (!_imageScroll) {
        _imageScroll = [[UIScrollView alloc]init];
        _imageScroll.backgroundColor=[UIColor blackColor];
        //imageScroll.center = button.center;
        _imageScroll.frame = CGRectMake(0, 0, 0, 0);
        _imageScroll.center = button.center;
        _imageScroll.pagingEnabled = YES;
        _imageScroll.contentSize = CGSizeMake(self.view.frame.size.width * self.imageArray.count, self.view.frame.size.height);
        _imageScroll.contentOffset = CGPointMake(self.view.frame.size.width * (button.tag - 100), 0);
        UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
        [_imageScroll addGestureRecognizer:tap];
        
        [self.view addSubview:_imageScroll];
        [UIView animateWithDuration:0.25 animations:^{
            self->_imageScroll.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            for (int i = 0; i < self.imageArray.count; i++) {
                UIButton *b = (UIButton *)[self.imageScrollView viewWithTag:i + 100];
                UIImageView *img = [[UIImageView alloc]initWithImage:b.imageView.image];
                img.bounds = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * (self.cameraShowView.frame.size.height/self.cameraShowView.frame.size.width));
                img.center = CGPointMake(self.view.center.x + self.view.frame.size.width * i, self.view.center.y);
                
                [self->_imageScroll addSubview:img];
            }
            
        }];
    }
}

-(void )tapClick:(UITapGestureRecognizer *)tap{
    
    [UIView animateWithDuration:0.25 animations:^{
        self->_imageScroll.bounds = CGRectMake(0, 0, 0, 0);
        self->_imageScroll.center = [tap locationInView:self.view];
    }completion:^(BOOL finished) {
        [self->_imageScroll removeFromSuperview];
        self->_imageScroll = nil;
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    [self setUpCameraLayer];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.session) {
        [self.session startRunning];
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    if (self.session) {
        [self.session stopRunning];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
